<template>
  <div>
    <ay-aside :page-info="pageInfo" />
    <div class="app-container">
      <div class="filter-container">

        <el-collapse v-model="filterNameKey" @change="handleChange">
          <el-collapse-item title="筛选条件" name="1">
            <el-row>
              <el-input v-model="search.title" placeholder="商品标题" style="width: 200px;" class="filter-item" />
              <el-cascader v-model="search.typeList" :options="typeList" :props="{ checkStrictly: true }" @change="handleItemChange" />

              <el-date-picker
                v-model="submitTimeTemp"
                class="filter-item"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-row>
          </el-collapse-item>
        </el-collapse>

        <p />

        <el-button v-waves class="filter-item refresh-btn" icon="el-icon-refresh" @click="handleRefresh" />

        <el-button v-show="isShowFilterBtn" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button v-show="isShowFilterBtn" v-waves class="filter-item" type="danger" icon="el-icon-close" @click="handleReset">
          重置
        </el-button>

        <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves class="filter-item" type="danger" icon="el-icon-delete" :disabled="disabledDelBtn" @click="handleDelete(delIdArr)">
          删除
        </el-button>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        fit
        stripe
        border
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column label="#" align="center" width="90">
          <template slot-scope="{row}">
            <span>C{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" min-width="100px">
          <template slot-scope="{row}">
            <span>{{ row.title }}</span>
          </template>
        </el-table-column>

        <el-table-column label="图片" min-width="180px">
          <template scope="scope">
            <img :src="scope.row.pic" width="120" class="head_pic">
          </template>
        </el-table-column>

        <el-table-column label="类型" min-width="200px">
          <template slot-scope="{row}">
            <span>{{ row.pName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" width="100px">
          <template slot-scope="{row}">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" width="100px">
          <template slot-scope="{row}">
            <span>{{ row.updateTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="handleDelete([row.id])" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pageTotal > 0" :total="pageTotal" :page.sync="pageNum" :limit.sync="pageSize" @pagination="getList" />

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="所属分类：" prop="roleid">
            <el-cascader v-model="temp.relations" :options="typeList" clearable filterable check-strictly :props="{ checkStrictly: true }" @change="handleItemChange" />

          </el-form-item>
          <el-form-item label="标题：" prop="title">
            <el-input v-model="temp.title" placeholder="输入标题" />
          </el-form-item>

          <el-form-item label="图片：" prop="pic">
            <el-input v-model="temp.pic" placeholder="输入图片" />
            <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="temp.pic" :src="temp.pic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>

          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelVisible"
        width="30%"
      >
        <span>确定删除数据？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getList, getPage, save, deletInfo, uploadPath } from '@/api/c2cGoodsList'
import { deepClone } from '@/utils/index'
import waves from '@/directive/waves' // waves directive
import AyAside from '@/components/Aside'
import Pagination from '@/components/Pagination'
export default {
  name: 'TypeList',
  components: { AyAside, Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {

      submitTimeTemp: '', // 提交时间中间量
      props: { // 下拉树配置项（必选）
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: true,
        checkStrictly: true
      },
      search: {
        title: '', // 店铺名称
        typeList: '', // 签约状态
        submitTime: '', // 提交时间
        startTime: '',
        endTime: '',
        typeId: ''
      },
      http: process.env.VUE_APP_BASE_API,
      isShowFilterBtn: true,
      uploadPath: '',
      filterNameKey: '1',
      isClearable: true, // 下拉树可清空（可选）
      isAccordion: true, // 下拉树可收起（可选）
      typeList: [],
      disabledDelBtn: true,
      dialogIconVisible: false,
      dialogDelVisible: false,
      pageInfo: {},
      list: null,
      listLoading: true,
      selectList: null,
      delIdArr: [],
      temp: {
        id: undefined,
        title: '',
        typeId: '',
        relations: '',
        createTime: '',
        updateTime: '',
        delFlag: 0,
        pic: ''
      },
      tableData: [],
      toggleSwitch: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'change' }],
        pic: [{ required: true, message: '图片不能为空', trigger: 'change' }]
      },
      userName: '',
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0
    }
  },
  watch: {
    submitTimeTemp(newval, oldval) {
      if (!newval) {
        this.search.submitTime = ''
      } else {
        const start = new Date(this.submitTimeTemp[0])
        const resStartDate = start.getFullYear() + '-' + this.doTwoDate((start.getMonth() + 1)) + '-' + this.doTwoDate(start.getDate())
        const resStartTime = this.doTwoDate(start.getHours()) + ':' + this.doTwoDate(start.getMinutes()) + ':' + this.doTwoDate(start.getSeconds())
        const end = new Date(this.submitTimeTemp[1])
        const resEndDate = end.getFullYear() + '-' + this.doTwoDate((end.getMonth() + 1)) + '-' + this.doTwoDate(end.getDate())
        const resEndTime = this.doTwoDate(end.getHours()) + ':' + this.doTwoDate(end.getMinutes()) + ':' + this.doTwoDate(end.getSeconds())
        this.search.startTime = `${resStartDate} ${resStartTime}`
        this.search.endTime = `${resEndDate} ${resEndTime}`
      }
    }
  },
  created() {
    this.getList()
    this.pageInfo = this.$route.meta
  },
  mounted() {
    this.uploadPath = uploadPath
  },
  methods: {
    sortFun(a) {
      console.log(a)
    },
    handleItemChange(item) {
      if (item) { this.temp.typeId = item[item.length - 1] }
    },
    // 获取表格数据接口
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        if (this.search.typeList) { this.search.typeId = this.search.typeList[this.search.typeList.length - 1] }

        const param = {}
        Object.assign(param, {

          pageNum: this.pageNum,
          pageSize: this.pageSize
        }, this.search)

        getPage(param).then(response => {
          console.log(response)

          getList({}).then((response) => {
            this.typeList = response.data
          })
          if (response.data.list) this.list = response.data.list
          this.pageTotal = response.data.total
          this.pageSize = response.data.pageSize
          this.pageNum = response.data.pageNum
          const cloneData = deepClone(this.list)
          this.tableData = cloneData
          this.listLoading = false
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
            resolve(true)
          }, 500)
        }).catch(error => {
          this.$message({
            message: error,
            type: 'error'
          })
          reject(false)
        })
      }
      )
    },
    // 刷新
    async handleRefresh() {
      if (await this.getList()) {
        this.$message({
          message: '刷新成功',
          type: 'success'
        })
      }
    },
    // 处理日期
    doTwoDate(s) {
      return s < 10 ? '0' + s : s
    },
    // 新增操作
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 表格选中时触发
    handleSelectionChange(selection) {
      this.delIdArr = []
      if (selection.length) {
        this.disabledDelBtn = false
        for (const i in selection) {
          this.delIdArr.push(selection[i].id)
        }
      } else {
        this.disabledDelBtn = true
      }
    },

    // 初始化表单
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        typeId: '',
        relations: '',
        createTime: '',
        updateTime: '',
        pic: '',
        delFlag: 0
      }
    },
    handleReset() {
      this.search = {
        title: '', // 店铺名称
        typeList: '', // 签约状态
        submitTime: '', // 提交时间
        startTime: '',
        endTime: '',
        typeId: ''
      }
      this.submitTimeTemp = ''
      this.pageNum = 1
      this.getList()
    },
    // 筛选查询操作
    handleSearch() {
      this.pageNum = 1
      this.getList()
    },
    // 新增数据接口
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.temp).then((response) => {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 编辑操作
    handleUpdate(row) {
      console.log(row, 'rrr')
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      console.log(this.temp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据接口
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.temp).then((response) => {
            this.$message({
              message: '更新成功',
              type: 'success'
            })
          }).finally(() => {
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    // 删除操作
    handleDelete(idArr) {
      this.dialogDelVisible = true
      this.delIdArr = idArr
    },
    deleteData() {
      deletInfo(this.delIdArr).then(() => {
        this.dialogDelVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleChange(val) {
      if (val.length === 0) {
        this.isShowFilterBtn = false
      } else {
        this.isShowFilterBtn = true
      }
    },

    handleAvatarSuccess(res, file) {
      this.temp.pic = res.data.url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'

      const isPng = file.type === 'image/png'

      console.log(file.type)

      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG|PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPng) && isLt2M
    }
  }
}

</script>

<style>

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    padding-top: 10px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: auto;
    line-height: auto;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: auto;
    display: block;
  }
  .el-cascader {
    display: inline-block;
    position: relative;
    font-size: 14px;
    line-height: 40px;
    margin-bottom: 10px;
    vertical-align: middle;
}
</style>

